<template>
    <section>
        <el-col id="mychina">
        </el-col>
        <el-col id="select" :style="highlight">
            <div class="select_ul">
                <div class="select_ul_li" @click="getTime(1,'radius1','text1')">
                    <span id="radius1" class="radius"></span>
                    <span id="text1" class="li_text">本周</span>
                </div>
                <div class="select_ul_li" @click="getTime(2,'radius2','text2')">
                    <span id="radius2" class="radius"></span>
                    <span id="text2" class="li_text">本月</span>
                </div>
                <div class="select_ul_li" @click="getTime(3,'radius3','text3')">
                    <span id="radius3" class="radius"></span>
                    <span id="text3" class="li_text">本年</span>
                </div>
            </div>
        </el-col>
    </section>
</template>
<script>
import echarts from 'echarts'
import 'echarts/map/js/china.js'
import commons from '../common/js/common'
import { mapState, mapActions } from 'vuex'
import { visitsCount } from '../api/api';
import unfoldLogo from '../assets/unfold.png'
import packupLogo from '../assets/packup.png'
export default {
    data() {
        return {
            mainLeft: '',
            filters: {
                Time: '',
                startDate: '',
                endDate: ''
            },
            mapobj: '',
            mychina: '',
            geoCoordMap: {
                // "北京": [116.46, 39.92],
                // "南京": [118.78, 32.04],
                // "吉林": [126.57, 43.87],
                // "上海": [121.48, 31.22],
                // "成都": [104.06, 30.67],
                // "哈尔滨": [126.63, 45.75],
                // "沈阳": [123.38, 41.8],
                // // "合肥":[117.27,31.86],
                // "武汉": [114.31, 30.52],
                // "石家庄": [114.48, 38.03],
                // "天津": [117.2, 39.13],
                // "太原": [112.53, 37.87],
                // "西安": [108.95, 34.27],
                // "南宁": [108.33, 22.84],
                // "南昌": [115.89, 28.68],
                // "济南": [117, 36.65],
            },
            data: [],
            selectedItems: [],
            categoryData: [],
            convertedData: [],
            barData: [],
            sum: 0,
            count: '',
            option: {}
        }
    },
    created() {

    },
    computed: mapState({
        clist: 'riskCodelist',
        blist: 'branchCodelist',
        Tourl: 'skipUrl',
        IsFirstURl: 'IsFirstURl',
        winHeight: 'winHeight',
        pclist: 'productCompanylist'
    }),
    methods: {
        ...mapActions([
            'CodeList', 'gainWH', 'ProductList', 'findProductCompanylist'
        ]),
        highlight: function () {
            var style = {
                'position': 'absolute',
                'top': '25px',
                'left': this.$store.state.mainLeft
            };
            return style;
        },
        getTime: function (num, id1, id2, all) {
            $('.radius').css('backgroundColor', '#999999');
            $('.li_text').css('color', '#999999');
            $('#' + id1).css('backgroundColor', '#20a0ff');
            $('#' + id2).css('color', '#20a0ff');
            function timeFormat(date) {
                if (!date || typeof (date) === "string") {
                    this.error("参数异常，请检查...");
                }
                var y = date.getFullYear(); //年
                var m = date.getMonth() + 1; //月
                var d = date.getDate(); //日

                return y + "-" + m + "-" + d;
            };
            //获取这周的周一
            function getFirstDayOfWeek(date) {

                var weekday = date.getDay() || 7; //获取星期几,getDay()返回值是 0（周日） 到 6（周六） 之间的一个整数。0||7为7，即weekday的值为1-7

                date.setDate(date.getDate() - weekday);//往前算（weekday-1）天，年份、月份会自动变化
                return timeFormat(date);
            };
            //获取当月第一天
            function getFirstDayOfMonth(date) {
                date.setDate(1);
                return timeFormat(date);
            };
            //获取当年第一天
            function getFirstDayOfYear(date) {
                date.setDate(1);
                date.setMonth(0);
                return timeFormat(date);
            };

            let nowTime = new Date();
            let nowDate;
            if (num == 1) {
                nowDate = getFirstDayOfWeek(nowTime) + ' ' + "00:00:00";
            }
            else if (num == 2) {
                nowDate = getFirstDayOfMonth(nowTime) + ' ' + "00:00:00";
            }
            else if (num == 3) {                getFirstDayOfMonth
                nowDate = getFirstDayOfYear(nowTime) + ' ' + "00:00:00";
            }
            if (all) {
                this.getEcharts(num, nowDate, all);
            } else {
                this.getEcharts(num, nowDate)
            }
        },
        convertData: function (data) {
            let _this = this;
            var res = [];
            for (var i = 0; i < data.length; i++) {
                var geoCoord = _this.geoCoordMap[data[i].name];
                if (geoCoord) {
                    res.push({
                        name: data[i].name,
                        value: geoCoord.concat(data[i].value)
                    });
                }
            }
            return res;
        },
        initialValue: function () {

        },
        resizeWorldMapContainer: function () {
            let _this = this;
            _this.mychina.style.width = (window.innerWidth - 205) + 'px';
            _this.mychina.style.height = (window.innerHeight - 40) + 'px';
        },
        renderBrushed: function (params) {
            let _this = this;
            var mainSeries = params.batch[0].selected[0];
            var selectedItems = [];
            var categoryData = [];
            var barData = [];
            var maxBar = 30;
            var sum = 0;
            var count = 0;

            for (var i = 0; i < mainSeries.dataIndex.length; i++) {
                var rawIndex = mainSeries.dataIndex[i];
                var dataItem = _this.convertedData[0][rawIndex];
                var pmValue = dataItem.value[2];
                sum += pmValue;
                count++;
                selectedItems.push(dataItem);
            }

            selectedItems.sort(function (a, b) {
                return a.value - b.value;
            });

            for (var i = 0; i < Math.min(selectedItems.length, maxBar); i++) {
                categoryData.push(selectedItems[i].name);
                barData.push(selectedItems[i].value[2]);
            }

            _this.mapobj.setOption({
                yAxis: {
                    data: categoryData
                },
                xAxis: {
                    axisLabel: {
                        show: !!count
                    }
                },
                title: {
                    id: 'statistic',
                    text: count ? '平均: ' + (sum / count).toFixed(4) : ''
                },
                series: {
                    id: 'bar',
                    data: barData
                }
            });
        },
        getEcharts: function (type, starttime, all) {
            let _this = this;
            let para = new FormData();
            let temptime = Date.parse(new Date());
            var startDate, endDate;
            let thisShow = true;
            let thisTitle = "查看全部";
            let isAll = true;
            let thisLogo = unfoldLogo;

            startDate = starttime;
            endDate = commons.getDaytime(temptime, 1, false);
            if (type == 1) {
                para.append('type', 'week');
            } else if (type == 2) {
                para.append('type', 'month');
            } else if (type == 3) {
                para.append('type', 'year');
            }

            visitsCount(para).then((res) => {
                _this.data = [];
                _this.geoCoordMap = {};
                _this.categoryData = [];
                _this.sum = 0;
                if (res.data.result) {
                    let datas = res.data.result;
                    if (all == 1) {
                        isAll = true;
                        thisTitle = "收起";
                        thisLogo = packupLogo;
                    } else if (all == 2) {
                        datas = datas.slice(0, 10);
                        isAll = false;
                        thisTitle = "查看全部";
                        thisLogo = unfoldLogo;
                    } else {
                        if (datas.length > 10) {
                            datas = datas.slice(0, 10);
                            thisShow = true;
                            isAll = false;
                        } else {
                            thisShow = false;
                        }
                    }

                    for (var i in datas) {
                        _this.geoCoordMap[datas[i].cityId] = [datas[i].longitude, datas[i].latitude];
                        _this.data.push({
                            name: datas[i].cityId,
                            value: datas[i].count
                        });
                    }
                }

                _this.count = _this.data.length;
                _this.convertedData = [
                    _this.convertData(_this.data),
                    _this.convertData(_this.data.sort(function (a, b) {
                        return b.value - a.value;
                    }).slice(0, 6))
                ];
                _this.data.sort(function (a, b) {
                    return a.value - b.value;
                });

                for (var i = 0; i < _this.data.length; i++) {
                    _this.categoryData.push(_this.data[i].name);
                    _this.barData.push(_this.data[i].value);
                    _this.sum += _this.data[i].value;
                }


                _this.option = {
                    backgroundColor: '#0F082E',
                    animation: true,
                    animationDuration: 1000,
                    animationEasing: 'cubicInOut',
                    animationDurationUpdate: 1000,
                    animationEasingUpdate: 'cubicInOut',
                    title: [{
                        text: '访问量',
                        left: 'center',
                        textStyle: {
                            color: '#fff'
                        }
                    },
                    {
                        id: 'statistic',
                        text: _this.count ? '平均: ' + parseInt((_this.sum / _this.count).toFixed(4)) : '',
                        right: 120,
                        top: 40,
                        width: 100,
                        textStyle: {
                            color: '#fff',
                            fontSize: 16
                        }
                    }],
                    toolbox: {
                        iconStyle: {
                            normal: {
                                borderColor: '#fff'
                            },
                            emphasis: {
                                borderColor: '#b1e4ff'
                            }
                        },
                        right: '1%',
                        feature: {
                            myTool: {
                                show: thisShow,
                                title: thisTitle,
                                icon: 'image://' + thisLogo,
                                onclick: function () {
                                    let allRadius = $('.radius');
                                    let thisNum = 1;
                                    $.each(allRadius, function (i, j) {
                                        let thisIndex = i + 1;
                                        let thisColor = $('#radius' + thisIndex).attr('style');
                                        if (thisColor == 'background-color: rgb(32, 160, 255);') {
                                            thisNum = thisIndex;
                                        }
                                    });
                                    if (isAll) {
                                        if (thisNum == 1) {
                                            _this.getTime(1, 'radius1', 'text1', 2);
                                        } else if (thisNum == 2) {
                                            _this.getTime(2, 'radius2', 'text2', 2);
                                        } else if (thisNum == 3) {
                                            _this.getTime(3, 'radius3', 'text3', 2);
                                        }
                                        isAll = false;
                                    } else {
                                        if (thisNum == 1) {
                                            _this.getTime(1, 'radius1', 'text1', 1);
                                        } else if (thisNum == 2) {
                                            _this.getTime(2, 'radius2', 'text2', 1);
                                        } else if (thisNum == 3) {
                                            _this.getTime(3, 'radius3', 'text3', 1);
                                        }
                                        isAll = true;
                                    }
                                }
                            }
                        }
                    },
                    geo: {
                        map: 'china',
                        left: '10',
                        right: '25%',
                        top: '10',
                        center: [117.98561551896913, 31.205000490896193],
                        zoom: 0.7,
                        label: {
                            emphasis: {
                                show: false
                            }
                        },
                        roam: true,
                        itemStyle: {
                            normal: {
                                borderWidth: 0.5,
                                shadowBlur: 50,
                                shadowColor: 'rgba(50,103,213, 0.3)',
                                areaColor: '#0E0930',
                                borderColor: '#3369D9'
                            },
                            emphasis: {
                                areaColor: '#3369D9',
                                opacity: 0.2
                            }
                        }
                    },
                    tooltip: {
                        trigger: 'item'
                    },
                    grid: [{
                        right: 80,
                        top: 100,
                        bottom: 40,
                        width: '20%',
                        height: this.winHeight - 200
                    }],
                    xAxis: {
                        type: 'value',
                        scale: true,
                        position: 'top',
                        boundaryGap: false,
                        splitLine: {
                            show: false
                        },
                        axisLine: {
                            show: false
                        },
                        axisTick: {
                            show: false
                        },
                        axisLabel: {
                            margin: 2,
                            textStyle: {
                                color: '#aaa'
                            }
                        },
                    },
                    yAxis: {
                        type: 'category',
                        nameGap: 16,
                        axisLine: {
                            show: true,
                            lineStyle: {
                                color: '#ddd'
                            }
                        },
                        axisTick: {
                            show: false,
                            lineStyle: {
                                color: '#ddd'
                            }
                        },
                        axisLabel: {
                            interval: 0,
                            textStyle: {
                                color: '#ddd'
                            }
                        },
                        data: _this.categoryData
                    },
                    series: [{
                        type: 'scatter',
                        coordinateSystem: 'geo',
                        data: _this.convertedData[0],
                        symbolSize: function (val) {
                            return Math.max(val[2] / 50000, 8);
                        },
                        label: {
                            normal: {
                                formatter: '{b}',
                                position: 'right',
                                show: false
                            },
                            emphasis: {
                                show: true
                            }
                        },
                        itemStyle: {
                            normal: {
                                color: '#efefef',
                                shadowColor: '#258CF9',
                                position: 'right',
                                show: true
                            }
                        }
                    }, {
                        type: 'effectScatter',
                        coordinateSystem: 'geo',
                        data: _this.convertedData[0],
                        symbolSize: function (val) {
                            return Math.max(val[2] / 50000, 8);
                        },
                        showEffectOn: 'emphasis',
                        rippleEffect: {
                            brushType: 'stroke'
                        },
                        hoverAnimation: true,
                        label: {
                            normal: {
                                formatter: '{b}',
                                position: 'right',
                                show: true
                            }
                        },
                        itemStyle: {
                            normal: {
                                color: '#258CF9',
                                shadowBlur: 10,
                                shadowColor: '#258CF9'
                            }
                        },
                        zlevel: 1
                    }, {
                        id: 'bar',
                        zlevel: 2,
                        type: 'bar',
                        symbol: 'none',
                        itemStyle: {
                            normal: {
                                color: '#258CF9'
                            }
                        },

                        data: _this.data
                    }
                    ]
                };

                var myChart = echarts.init(document.getElementById('mychina'));
                _this.mapobj = myChart;
                myChart.on('brushselected', _this.renderBrushed);
                myChart.setOption(_this.option);
            });
        }
    },
    mounted() {
        let _this = this;
        // _this.store.state.count++;
        var worldMapContainer = document.getElementById('mychina');
        _this.mychina = worldMapContainer;
        _this.$store.commit('GET_ECAHRTOBJ', worldMapContainer);
        _this.resizeWorldMapContainer();
        _this.$nextTick(function () {
            _this.getTime(1, 'radius1', 'text1');
        });
        _this.CodeList('RiskCode');
        _this.CodeList('BranchCode');
        _this.ProductList('');
        _this.gainWH();
        _this.findProductCompanylist();


        try {
            window.onresize = function () {
                _this.resizeWorldMapContainer();
                _this.mapobj.resize();
            };
        }
        catch (error) {

        }



    }
}
</script>

<style scoped>
.content-container {
  padding-top: 0px !important;
  position: relative;
}
#mychina {
}
#select {
  width: 80%;
  position: absolute;
  top: 5px;
}
.select_ul {
  margin-left: 10px;
}
.select_ul_li {
  display: block;
  width: 100px;
  height: 30px;
  line-height: 30px;
  color: #999999;
  cursor: pointer;
}
.select_ul_li .radius {
  display: inline-block;
  width: 15px;
  height: 15px;
  border-radius: 10px;
  background-color: #999999;
}
.li_text {
  display: inline-block;
  width: 40px;
  height: 20px;
  /*border:1px red solid;*/
  box-sizing: border-box;
  margin-left: 10px;
  font-size: 14px;
}
/*.el-button{
    padding:5px 10px !important;
}*/
</style>